//格式化时间
function dateFtt(fmt,date)   
{ //author: meizz   
  var o = {   
    "M+" : date.getMonth()+1,                 //月份   
    "d+" : date.getDate(),                    //日   
    "h+" : date.getHours(),                   //小时   
    "m+" : date.getMinutes(),                 //分   
    "s+" : date.getSeconds(),                 //秒   
    "q+" : Math.floor((date.getMonth()+3)/3), //季度   
    "S"  : date.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt))   
    fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));   
  for(var k in o)   
    if(new RegExp("("+ k +")").test(fmt))   
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
  return fmt;   
} 
function formatSubscribeTime(cellValue, options, rowObject) {
	var dateStr = "";
	if(cellValue){
		var crtTime = new Date(cellValue);
		dateStr = dateFtt("yyyy-MM-dd hh:mm:ss",crtTime);
	}
    return dateStr;
}
//加载字典
function dictJudge(value, options, row){
    //sex为自定义字典项
	var statusObj = vm.options.sex;
    for( var i=0;i< statusObj.length;i++ ){
        if(statusObj[i].value == value){
            return '<span>'+statusObj[i].text+'</span>' ;
        }
    }
}

function getRootPath(){
    //获取当前网址，如： http://localhost:8083/uimcardprj/share/meun.jsp
    var curWwwPath=window.document.location.href;
    //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
    var pathName=window.document.location.pathname;
    var pos=curWwwPath.indexOf(pathName);
    //获取主机地址，如： http://localhost:8083
    var localhostPaht=curWwwPath.substring(0,pos);
    //获取带"/"的项目名，如：/uimcardprj
    var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
    return(localhostPaht+projectName);//http://localhost:8083/uimcardprj
}

$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'convenienceSer/convenienceInfo/list',
        datatype: "json",
        colModel: [			
			{ label: '序号', name: 'id', index: 'id', width: 15, key: true },
            { label: '服务名称', name: 'serviceName', index: 'service_name', width: 25 },
            { label: '服务内容', name: 'content', index: 'content',
                formatter: function (cellvalue) {
                    // console.log(cellvalue);
                    // console.log("cellvalue:"+typeof(cellvalue));
                    var content = cellvalue.replace(/&amp;nbsp;/ig,' ');
                    return content;
                }},
            { label: '创建时间', name: 'createTime', index: 'create_date', width: 30,
                formatter:
                    function(cellvalue, options, row){
                        return dateFtt("yyyy-MM-dd",new Date(cellvalue))
                 }
                    }
            /*{ label: '发布状态', name: 'status', index: 'status', width: 25,
                formatter: function (cellvalue, options, rowObject) {
                    return cellvalue == 1 ? "已发布" : "未发布";
                }
            },*/

        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});


function datePlugin(){
    //初始化日期组件-年月日
    $('#publish_date').datepicker({
        language: 'zh-CN',//显示中文
        startView: 0, //选择器开始界面 0：天（默认 1：月2：年3：十年 4：世纪
        minViewMode: 0,//最小选择精度 0：天（最小默认）
        maxViewMode: 2, //最大选择精度 4：世纪（最大默认）
        format: 'yyyy-mm-dd',//显示格式
        minView: "day",//设置只显示到月份
        // initialDate: new Date(),
        autoclose: true,//选中自动关闭
        // todayBtn: true//显示今日按钮
        clearBtn: true, //清除按钮
        todayHighlight: true //今日高亮
    });
}


var vm = new Vue({
	el:'#rrapp',
	data:{
        q:{
            channel: ''
        },
		showList: true,
		title: null,
        convenience: {},
        channels:{}
	},
	methods: {
		query: function () {
			vm.reload();
		},
		/*add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.topic = {};

			vm.getChannels();


			datePlugin();
			//设置默认日期
            vm.topic.publishDate = dateFtt('yyyy-MM-dd',new Date());

            // 富文本编辑器--发布内容
            // var ue = UE.getEditor('editor');
            // UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
            // UE.Editor.prototype.getActionUrl = function(action) {
            //     if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadimage'
            //         || action == 'uploadvideo' || action == 'uploadfile') {
            //         return '${pageContext.request.contextPath}/ueditor/upload';
            //     }else {
            //         return this._bkGetActionUrl.call(this, action);
            //     }
            // };

            //手机缩略图
            $("#myFile").fileinput({
                language : 'zh',
                uploadUrl : baseURL + "common/file/upload/saveFile",
                // uploadUrl : "ueditor/upload/photo",
                autoReplace : true,
                maxFileCount : 1,
                allowedFileExtensions : [ "jpg", "png", "gif" ],
                browseClass : "btn btn-primary", //按钮样式
                previewFileIcon : "<i class='glyphicon glyphicon-king'></i>"
            }).on("filebatchselected", function(event, files) {
                $(this).fileinput("upload");

            }).on("fileuploaded", function(e, data) {
                var res = data.response;
                // console.log(111);
                // console.log(res);
                // alert(res.success);
                // document.getElementById("alogo").value=res.success;
                vm.topic.logo = res.fileList[0].url;
            });
		},*/
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";

            datePlugin();
            vm.getInfo(id);
            vm.getChannels();

            //富文本编辑器--发布内容
            // var ue = UE.getEditor('editor');
            UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
            UE.Editor.prototype.getActionUrl = function(action) {
                if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadimage'
                    || action == 'uploadvideo' || action == 'uploadfile') {
                    // return '${pageContext.request.contextPath}/ueditor/upload';
                    return getRootPath() + '/common/file/upload/ueSaveFile';
                }else {
                    return this._bkGetActionUrl.call(this, action);
                }
            };

            /*  //手机缩略图
              $("#myFile").fileinput({
                  language : 'zh',
                  uploadUrl : baseURL + "common/file/upload/saveFile",
                  // uploadUrl : "${request.contextPath}/ueditor/upload/photo",
                  autoReplace : true,
                  maxFileCount : 1,
                  allowedFileExtensions : [ "jpg", "png", "gif" ],
                  browseClass : "btn btn-primary", //按钮样式
                  previewFileIcon : "<i class='glyphicon glyphicon-king'></i>",
                  initialPreview: [
                      "<img src=${vm.topic.logo} class='file-preview-image' />"],

              }).on("filebatchselected", function(event, files) {
                  $(this).fileinput("upload");
              }).on("fileuploaded", function(e, data) {
                  var res = data.response;
                  // console.log(222);
                  // console.log(res);
                  // alert(res.success);
                vm.topic.logo=res.fileList[0].url;
            });*/
		},
		saveOrUpdate: function (event) {
            var url ="convenienceSer/convenienceInfo/update";

            var ue = UE.getEditor('editor');
            vm.convenience.content =encodeURI(ue.getContent());
            /*var content = vm.convenience.content;
            vm.convenience.content = content.replace(/&amp;nbsp;/ig," ");*/

            console.log("content---"+vm.convenience.content);

            $.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.convenience),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
						});
						console.log("JSONtopic-----"+JSON.stringify(vm.convenience));
					}else{
						alert(r.msg);
                        console.log(JSON.stringify(vm.convenience));

                    }
				}
			});
		},
		/*del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "news/topic/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},*/

        getInfo: function(id){
			$.get(baseURL + "convenienceSer/convenienceInfo/info/"+id, function(r){
                /*console.log(r);
			    console.log("before:"+r.convenience);
			    console.log("before:"+r.convenience.content);
			    console.log("r.convenience.content:"+typeof(r.convenience.content));*/
                var content = r.convenience.content;
                r.convenience.content = content.replace(/&amp;nbsp;/ig,' ');
			    // console.log("after:"+r.convenience.content);
			    vm.convenience = r.convenience;
                //日期格式化
                vm.convenience.publishDate = dateFtt("yyyy-MM-dd",new Date(vm.convenience.createTime));
                //富文本--内容
                UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
                UE.Editor.prototype.getActionUrl = function(action) {
                    if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadimage'
                        || action == 'uploadvideo' || action == 'uploadfile') {
                        // return '${request.contextPath}/ueditor/upload';
                        return getRootPath() + '/common/file/upload/ueSaveFile';
                    }else {
                        return this._bkGetActionUrl.call(this, action);
                    }
                };
                ue.ready(function(){//监听编辑器实例化完成的事件
                    ue.setContent("");
                    ue.setContent(vm.convenience.content);
                });
            });
		},

        //获取所有公告类型
        getChannels: function(){
            $.get(baseURL + "news/channel/list", function(r){
                vm.channels = r.page.list;

            });
        },

		reload: function (event) {
			vm.showList = true;
			ue.setContent("");
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{'cname': vm.q.channel},
                page:page
            }).trigger("reloadGrid");
		}
	}
});

vm.getChannels();